package cn.cf.kxx.tools;

import android.content.Context;
import android.util.Log;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.Timer;
import java.util.TimerTask;

import cn.cf.kxx.MainActivity2;
import cn.cf.kxx.data.DataSharedPreferences;
import cn.cf.kxx.model.comm.MqMessage;

public class MQTTUtils {

    public static final String TAG = "MQTTUtils";

    private MqttAndroidClient client;
    private MqttConnectOptions conOpt;

    private String host = "tcp://116.204.121.65:1883";
    private String userName = "kxh";
    private String passWord = "admin";
    private String devBh = "NULLID";      //要订阅的主题
    private String clientId;//客户端标识
    private String serverTopic = "serverWin";// 服务端主题
    private String willTopic = "heartBeat";//
    private String registTopic = "deviceRegister";//注册topic
    boolean doConnect = true;

    Context context;

    static MQTTUtils mqttUtils = null;

    MqttCallback mqttCallback;
    MqMessage mqMessage = new MqMessage();

    public MQTTUtils(Context context,String devBh, MqttCallback mqttCallback){
        this.context = context;
        this.clientId = Tools.getDeviceId(context);
        this.mqttCallback=mqttCallback;
        this.devBh = devBh;
        mqMessage.setDevBh(devBh);
        initOption();

    }

    public void connecting(){
        if(doConnect){
            doConnect = false;
            connect();
        }

    }


    private void initOption(){
        conOpt = new MqttConnectOptions();
        //断开自动重连
        conOpt.setAutomaticReconnect(true);
        // 清除缓存
        conOpt.setCleanSession(true);
        // 设置超时时间，单位：秒
        conOpt.setConnectionTimeout(10);
        // 心跳包发送间隔，单位：秒
        conOpt.setKeepAliveInterval(20);
        // 用户名
        conOpt.setUserName(userName);
        // 密码
        conOpt.setPassword(passWord.toCharArray());     //将字符串转换为字符串数组
        //心跳时间 单位：秒
        conOpt.setKeepAliveInterval(60);
        //选择版本
        conOpt.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
    }


    public static MQTTUtils getInstance(Context context,String devBh, MqttCallback mqttCallback){
        if(mqttUtils == null){
            mqttUtils = new MQTTUtils(context,devBh,mqttCallback);
        }
        return mqttUtils;
    }

    public void registDevice(String msg) {
        try {
            if (client != null) {
                client.publish(registTopic, msg.getBytes(), 0, false);
            }
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public void heartBeat() {
        try {
            if (client != null) {
                mqMessage.setType(0);
                mqMessage.setMsg("设备心跳");
                client.publish(willTopic, Tools.gson.toJson(mqMessage).getBytes(), 0, false);
            }
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }


    public void publish(String msg) {
        try {
            if (client != null) {
                client.publish("deviceData", msg.getBytes(), 0, false);
            }
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    private void connect() {
        // 服务器地址（协议+地址+端口号）
        client = new MqttAndroidClient(context, host, clientId);
        // 设置MQTT监听并且接受消息
        client.setCallback(mqttCallback);
        //
        setWill();
        //
        doClientConnection();
    }

    private void setWill(){
        // last will message
        mqMessage.setType(-1);
        mqMessage.setMsg("设备掉线");

        // 最后的遗嘱
        // MQTT本身就是为信号不稳定的网络设计的，所以难免一些客户端会无故的和Broker断开连接。
        //当客户端连接到Broker时，可以指定LWT，Broker会定期检测客户端是否有异常。
        //当客户端异常掉线时，Broker就往连接时指定的topic里推送当时指定的LWT消息。
        //QTT定义了三个QoS等级，分别为：QoS 0，最多交付一次。QoS 1，至少交付一次。QoS 2，只交付一次
        /**
         * 参数说明：
         * topic：指定遗嘱消息发布的主题。
         * payload：遗嘱消息的内容，以字节数组形式表示。
         * qos：遗嘱消息的服务质量等级，取值为0、1或2。
         * retained：是否将遗嘱消息保留在Broker上，如果设为true，则即使客户端重新连接，也会收到这个遗嘱消息。
         */
        try {
            conOpt.setWill(willTopic, Tools.gson.toJson(mqMessage).getBytes(), 0, false);
        } catch (Exception e) {
            doConnect = false;
            iMqttActionListener.onFailure(null, e);
        }
    }


    public void close(){
        if (client != null) {
            client.unregisterResources();
            client.close();
            client = null;
        }
    }

    /**
     * 连接MQTT服务器
     */
    private void doClientConnection() {
        if (!client.isConnected() && Tools.isConnectIsNormal(context)) {
            try {
                IMqttToken iMqttToken = client.connect(conOpt, null, iMqttActionListener);
                Log.e(TAG,"MessageId"+iMqttToken.getMessageId());
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
    }

    // MQTT是否连接成功
    private IMqttActionListener iMqttActionListener = new IMqttActionListener() {

        @Override
        public void onSuccess(IMqttToken arg0) {
            try {
                // 订阅自己的话题
                Log.e(TAG,"MQTT链接成功");
                IMqttToken iMqttToken = client.subscribe(devBh, 0);

                mqMessage.setDevBh(devBh);
                mqMessage.setType(1);
                mqMessage.setMsg("设备注册");
                registDevice(Tools.gson.toJson(mqMessage));

            } catch (MqttException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(IMqttToken arg0, Throwable arg1) {
            Log.e(TAG,"MQTT链接失败");
            arg1.printStackTrace();
            // 连接失败，重连
//            doClientConnection();
        }
    };




//    private static final int NOTIFICATION_ID = 2;
//
//    public void toCreateNotification(String message) {
//        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, new Intent(this, MQTTService.class), PendingIntent.FLAG_UPDATE_CURRENT);
//        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);//3、创建一个通知，属性太多，使用构造器模式
//
//        Notification notification = builder
//                .setTicker("测试标题")
//                .setSmallIcon(R.mipmap.ic_launcher)
//                .setContentTitle("")
//                .setContentText(message)
//                .setContentInfo("")
//                .setContentIntent(pendingIntent)//点击后才触发的意图，“挂起的”意图
//                .setAutoCancel(true)        //设置点击之后notification消失
//                .build();
//        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//        startForeground(NOTIFICATION_ID, notification);
//        notificationManager.notify(0, notification);
//    }
}